<template>
  <a-layout style="padding: 10px">
    <a-layout-content
      :style="{ background: '#fff', padding: '10px', margin: 0, minHeight: '280px' }"
    >
      <a-flex vertical gap="small">
        <a-row>
          <a-button type="primary" @click="showDrawer">
            <template #icon><PlusOutlined /></template>
            添加商品
          </a-button>
        </a-row>
        <a-row>
          <a-col :span="24">
            {{ pageRef }}
            <a-table :data-source="goodsListRef" :columns="goodsListColumns" :pagination="false" />
          </a-col>
        </a-row>
        <a-row justify="end">
          <a-col :span="8" style="text-align: end">
            <a-pagination
              v-model:current="pageRef.page"
              :total="total"
              :page-size="pageRef.pageSize"
              @change="handleTablePageChangeFunc"
              :show-total="(total: number) => `共 ${total} 条`"
            />
          </a-col>
        </a-row>
      </a-flex>
      <a-drawer title="添加商品" width="80%" :open="openDrawRef" @close="onClose">
        <a-flex gap="middle" vertical>
          <a-steps :current="current" :items="items" />
          <a-form
            ref="addGoodsFormModelRef"
            :model="addGoodsFormModel"
            layout="horizontal"
            v-show="current === 0"
            :labelWrap="true"
            :label-col="{ span: 3 }"
            label-align="left"
          >
            <a-row :span="24">
              <a-col :span="24" style="text-align: left">
                <a-form-item label="销量类型" :name="['priceInfo', 'salesType']">
                  <a-radio-group
                    v-model:value="addGoodsFormModel.priceInfo.salesType"
                    button-style="solid"
                  >
                    <a-radio-button value="EXACT">精确</a-radio-button>
                    <a-radio-button value="ROUGH">模糊</a-radio-button>
                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="标题"
                  :name="['baseInfo', 'title']"
                  :rules="[{ required: true, max: 512 }]"
                >
                  <a-input
                    v-model:value="addGoodsFormModel.baseInfo.title"
                    placeholder="请输入标题"
                  />
                </a-form-item>
                <a-form-item
                  label="子标题"
                  :name="['baseInfo', 'subTitle']"
                  :rules="[{ required: true, max: 512 }]"
                >
                  <a-input
                    v-model:value="addGoodsFormModel.baseInfo.subTitle"
                    placeholder="请输入子标题"
                  />
                </a-form-item>
                <a-form-item
                  label="父分类名称"
                  :name="['baseInfo', 'categoryId']"
                  :rules="[{ required: true }]"
                >
                  <CategorySelect
                    @category:selected="
                      (categoryId) => (addGoodsFormModel.baseInfo.categoryId = categoryId)
                    "
                  />
                </a-form-item>
                <a-form-item
                  label="商品主图"
                  :name="['baseInfo', 'mainImage']"
                  :rules="[{ required: true }]"
                >
                  <a-upload
                    v-model:file-list="addGoodsFormModel.baseInfo.mainImage"
                    list-type="picture-card"
                    :max-count="1"
                    action="http://127.0.0.1:20020/file-server/file/upload?bucket=bosi-mall-app-web&path=goods,image"
                  >
                    <div>
                      <plus-outlined />
                      <div style="margin-top: 8px">Upload</div>
                    </div>
                  </a-upload>
                </a-form-item>
                <a-form-item
                  label="轮播图"
                  :name="['baseInfo', 'carouselImage']"
                  :rules="[{ required: true }]"
                >
                  <a-upload
                    v-model:file-list="addGoodsFormModel.baseInfo.carouselImage"
                    list-type="picture-card"
                    :max-count="10"
                    action="http://127.0.0.1:20020/file-server/file/upload?bucket=bosi-mall-app-web&path=goods,image"
                  >
                    <div>
                      <plus-outlined />
                      <div style="margin-top: 8px">Upload</div>
                    </div>
                  </a-upload>
                </a-form-item>
                <a-form-item label="商品状态" name="status">
                  <a-radio-group
                    v-model:value="addGoodsFormModel.baseInfo.status"
                    button-style="solid"
                  >
                    <a-radio-button value="ON_SHELVES">上架</a-radio-button>
                    <a-radio-button value="DELISTED">下架</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-form
            ref="addGoodsFormModelRef"
            :model="addGoodsFormModel"
            layout="horizontal"
            v-show="current === 1"
            :label-col="{ span: 3 }"
            label-align="left"
          >
            <a-row :span="24">
              <a-col :span="24" style="text-align: left">
                <a-form-item label="销售量类型" :name="['priceInfo', 'salesType']">
                  <a-radio-group
                    v-model:value="addGoodsFormModel.priceInfo.salesType"
                    button-style="solid"
                  >
                    <a-radio-button value="EXACT">精确的</a-radio-button>
                    <a-radio-button value="ROUGH">模糊的</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24" style="text-align: left">
                <sku-add
                  @sku:changed="(skuItems) => (addGoodsFormModel.priceInfo.skus = skuItems)"
                />
              </a-col>
            </a-row>
          </a-form>
          <a-form
            v-show="current === 2"
            ref="addGoodsParamRef"
            name="dynamic_form_nest_item"
            :model="paramsValidateForm"
            @finish="onFinish"
          >
            <a-flex
              gap="small"
              v-for="(param, index) in paramsValidateForm.params"
              :key="param.id"
              align="left"
              direction="vertical"
            >
              <a-form-item
                :name="['params', index, 'name']"
                :rules="{
                  trigger: 'blur',
                  required: true,
                  min: 1,
                  message: '请输入属性名称',
                }"
              >
                <a-input v-model:value="param.name" placeholder="属性名称" />
              </a-form-item>
              <a-form-item
                :name="['params', index, 'description']"
                :rules="{
                  trigger: 'blur',
                  required: true,
                  min: 1,
                  message: '请输入属性描述',
                }"
              >
                <a-textarea
                  v-model:value="param.description"
                  show-count
                  :maxlength="255"
                  :auto-size="{ minRows: 2, maxRows: 5 }"
                />
              </a-form-item>
              <MinusCircleOutlined @click="removeUser(param)" />
            </a-flex>
            <a-form-item>
              <a-button type="dashed" block @click="addParam">
                <PlusOutlined />
                添加新属性
              </a-button>
            </a-form-item>
            <Tinymce v-model="content" width="100%" />
          </a-form>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-space-compact>
                <a-button v-if="current > 0" style="margin-left: 8px" @click="prev"
                  >上一步</a-button
                >
                <a-button v-if="current < steps.length - 1" type="primary" @click="next"
                  >Next</a-button
                >
                <a-button v-if="current == steps.length - 1" type="primary" @click="onSummitFunc">
                  提交
                </a-button>
              </a-space-compact>
            </a-col>
          </a-row>
        </a-flex>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts" setup>
  import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { reactive, ref, toRaw } from 'vue';
  import {
    AddGoodsRequest,
    GoodsItem,
    GoodsSearchRequest,
    GoodsSkuInfoRequest,
    ParamRequest,
  } from '#/goods-manage/goods-manage/goods';
  import CategorySelect from '@/my-components/CategorySelect.vue';
  import SkuAdd, { SkuTableBaseItem } from '@/my-components/sku/SkuAdd.vue';
  import { allUploadImage, firstUploadImage } from '@/utils/image/upload';
  import { UploadFile } from 'ant-design-vue/es/upload/interface';
  import { FormInstance } from 'ant-design-vue/lib/form/Form';
  import { Tinymce } from '@/components/Tinymce';
  import { addGoods, goods } from '@/api/goods-manage/goods-manage/goods';
  import { BasicFetchResult, BasicPageParams } from '@/api/model/baseModel';

  // 添加新商品抽屉表单展示或者隐藏
  const openDrawRef = ref<boolean>(false);
  // 添加商品展开抽屉
  const showDrawer = () => {
    openDrawRef.value = true;
  };
  // 添加商品抽屉表单展示或者隐藏
  const onClose = () => {
    openDrawRef.value = false;
  };

  // -----------------------------------------------------------------------------------------------
  // 创建商品的步骤
  const current = ref<number>(0);
  // 下一步
  const next = async () => {
    try {
      const values = toRaw(await addGoodsFormModelRef.value.validateFields()) as AddGoodsForm;
      console.log(values);
      current.value++;
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
      current.value++;
    }
  };
  const prev = () => {
    current.value--;
  };
  const steps = [
    {
      title: '商品基本信息',
      content: '商品基本信息',
    },
    {
      title: '商品SKU信息',
      content: '商品SKU信息',
    },
    {
      title: '商品属性',
      content: '商品属性',
    },
  ];
  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  // -----------------------------------------------------------------------------------------------

  // -----------------------------------------------------------------------------------------------
  // 创建商品
  type AddGoodsForm = {
    baseInfo: {
      carouselImage: UploadFile[];
      categoryId: number;
      goodsType: 'PHYSICAL_GOODS';
      mainImage: UploadFile[];
      subTitle: '';
      status: 'ON_SHELVES' | 'DELISTED';
      title: '';
    };
    paramsInfo: {
      params: [];
      tags: [];
    };
    priceInfo: {
      salesType: 'EXACT' | 'ROUGH';
      skus: SkuTableBaseItem[];
    };
    detailInfo?: {
      html: string;
    };
  };
  // 创建商品表单Model
  const addGoodsFormModel = reactive<AddGoodsForm>({
    baseInfo: {
      carouselImage: [],
      categoryId: 0,
      goodsType: 'PHYSICAL_GOODS',
      mainImage: [],
      subTitle: '',
      status: 'ON_SHELVES',
      title: '',
    },
    paramsInfo: { params: [], tags: [] },
    priceInfo: { salesType: 'EXACT', skus: [] },
  });

  const addGoodsFormModelRef = ref();

  // 新增商品提交按钮
  const onSummitFunc = async () => {
    const addGoodsRequest: AddGoodsRequest = {
      baseInfo: {
        carouselImage: allUploadImage(addGoodsFormModel.baseInfo.carouselImage),
        categoryId: addGoodsFormModel.baseInfo.categoryId,
        goodsType: addGoodsFormModel.baseInfo.goodsType,
        mainImage: firstUploadImage(addGoodsFormModel.baseInfo.mainImage),
        title: addGoodsFormModel.baseInfo.title,
        subTitle: addGoodsFormModel.baseInfo.subTitle,
      },
      priceInfo: {
        salesType: defaultSalesType(addGoodsFormModel.priceInfo.salesType),
        skus: toSku(addGoodsFormModel.priceInfo.skus),
      },
      paramsInfo: { tags: [], params: toParam(paramsValidateForm.value.params) },
      detailInfo: {
        html: content.value,
      },
    };
    console.log(addGoodsRequest);
    await addGoods(addGoodsRequest);
  };

  const defaultSalesType = (salesType: 'EXACT' | 'ROUGH' | undefined) => {
    if (salesType) {
      return salesType;
    }
    return 'EXACT';
  };

  const toSku = (skus: SkuTableBaseItem[]) => {
    const skuRequest: GoodsSkuInfoRequest[] = [];
    skus.map((sku) => {
      let skuItem = {
        price: sku.price,
        costPrice: sku.costPrice,
        linePrice: sku.linePrice,
        stock: sku.stock,
        description: sku.description,
        warnStock: sku.warnStock,
        status: sku.status,
        skuCode: sku.skuCode,
        image: firstUploadImage(sku.image),
      };
      // 遍历sku的其他属性
      Object.keys(sku).forEach((key) => {
        if (!Object.keys(skuItem).includes(key)) {
          skuItem['name'] = key;
          skuItem['description'] = sku.description;
        }
      });
      skuRequest.push(skuItem as GoodsSkuInfoRequest);
    });
    return skuRequest;
  };

  const toParam = (params: Param[]) => {
    const paramRequest: ParamRequest[] = [];
    params.map((param) => {
      let paramItem = {
        name: param.name,
        description: param.description,
      };
      paramRequest.push(paramItem);
    });
    return paramRequest;
  };
  // -----------------------------------------------------------------------------------------------
  // 新增商品参数
  interface Param {
    name: string;
    description: string;
    id: number;
  }
  const addGoodsParamRef = ref<FormInstance>();
  const paramsValidateForm = ref<{ params: Param[] }>({
    params: [],
  });
  const removeUser = (item: Param) => {
    const index = paramsValidateForm.value.params.indexOf(item);
    if (index !== -1) {
      paramsValidateForm.value.params.splice(index, 1);
    }
  };
  const addParam = () => {
    paramsValidateForm.value.params.push({
      name: '',
      description: '',
      id: Date.now(),
    });
  };
  const onFinish = (values) => {
    console.log('Received values of form:', values);
  };
  // 商品富文本详情------------------------------------------------------------------------------------------
  const content = ref();
  // 商品列表-----------------------------------------------------------------------------------------
  const goodsListRef = ref<GoodsItem[]>([]);
  const goodsListColumns = [
    {
      title: '商品图片',
      dataIndex: 'mainImage',
      key: 'mainImage',
    },
    {
      title: '商品标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '商品子标题',
      dataIndex: 'subTitle',
      key: 'subTitle',
    },
  ];
  // 查询商品
  const page: BasicPageParams = {
    page: 1,
    pageSize: 1,
  };
  const pageRef = ref(page);
  const total = ref(0);

  const populateData = async (page: BasicPageParams) => {
    const searchRequest: GoodsSearchRequest = {
      ...page,
    };
    goods(searchRequest).then((res: BasicFetchResult<GoodsItem>) => {
      total.value = res.total;
      goodsListRef.value = [...res.items];
    });
  };

  populateData(toRaw(pageRef));

  const handleTablePageChangeFunc = (current: number, pageSize: number) => {
    const page: BasicPageParams = {
      page: current,
      pageSize: pageSize,
    };
    populateData(page);
  };
</script>
